package consumer.controller;

import entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import vo.ResponseResult;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    private static String GLOBAL_URL="http://springcloud-nacos-provider/user";

    @PostMapping
    public ResponseResult add(User user){
        System.out.println("Consummer.UserController.add()");

        MultiValueMap param=new LinkedMultiValueMap();
        param.add("username",user.getUsername());
        param.add("password",user.getPassword());

        return restTemplate.postForObject(GLOBAL_URL,param,ResponseResult.class);
    }

    @DeleteMapping("/{id}")
    public ResponseResult remove(@PathVariable("id") Integer id){
        System.out.println("Consummer.UserController.remove()");

//        restTemplate.delete(GLOBAL_URL+"/{id}",id);
//
//        return ResponseResult.success();

        ResponseEntity<ResponseResult> responseEntity=restTemplate.exchange(GLOBAL_URL+"/{id}", HttpMethod.DELETE,null,ResponseResult.class,id);

        return responseEntity.getBody();
    }

    @PutMapping
    public ResponseResult modify(User user){
        System.out.println("Consummer.UserController.modify()");




        MultiValueMap param=new LinkedMultiValueMap();
        param.add("id",user.getId());
        param.add("username",user.getUsername());
        param.add("password",user.getPassword());


//        restTemplate.put(GLOBAL_URL,param);
//
//        return ResponseResult.success();

        HttpHeaders headers=new HttpHeaders();
//        headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<MultiValueMap> requestEntity=new HttpEntity<>(param,headers);

        ResponseEntity<ResponseResult> responseEntity=restTemplate.exchange(GLOBAL_URL,HttpMethod.PUT,requestEntity,ResponseResult.class);

        return responseEntity.getBody();

    }

    @GetMapping("/{id}")
    public ResponseResult findById(@PathVariable("id") Integer id){
        System.out.println("Consummer.UserController.findById()");
        return restTemplate.getForObject(GLOBAL_URL+"/{id}",ResponseResult.class,id);
    }

    @GetMapping
    public ResponseResult findAll(){
        System.out.println("Consummer.UserController.findAll()");
        return restTemplate.getForObject(GLOBAL_URL,ResponseResult.class);
    }

}



